import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from aws_model.athena_submit import submit
from config import result_bucket
from sql_lambda.delete import delete_data, addmonth
from base_class.inspect_logging import print_to_log
import datetime
import json
from aws_model.aws_stepfunc import send_task_success, send_task_failure


def result_iotwdfb(event):
    date = event.get('p_date')
    if not date:
        date = datetime.datetime.today().strftime('%Y-%m-%d')
    date = datetime.datetime.strptime(date, '%Y-%m-%d')
    last_month = (addmonth(date, -1)).strftime('%Y-%m-%d')
    year_month = '-'.join(last_month.split('-')[:2])
    date = date.strftime('%Y-%m-%d')
    table_name = sys._getframe().f_code.co_name
    delete_data(result_bucket, table_name, date)

    sql = f'''insert into fridge_biz_result.result_iotwdfb
            (
                select
                     upper(m.model) as model, temperature,
                     sum (freezeroomsensortempreture) as freezeroomsensortempreture,
                     sum (freezeroomtargettempreture) as freezeroomtargettempreture,
                     sum (coldroomsensortempreture) as coldroomsensortempreture,
                     sum (coldroomtargettempreture) as coldroomtargettempreture,
                     sum (changingroomtargettempreture) as changingroomtargettempreture,
                     sum (changingsensortempreture) as changingsensortempreture,
                     sum (evnsensortempreture) as evnsensortempreture,
                     sum (freezeroomevaporationsensortempreture) as freezeroomevaporationsensortempreture,
                     sum (changingroomevaporationsensortempreture) as changingroomevaporationsensortempreture,
                     sum (coldroomevaporationsensortempreture) as coldroomevaporationsensortempreture,
                     sum(sum(coldroomevaporationsensortempreture)) over(partition by time, upper(m.model)) as total_count,
                     time
                from
                     dws.fridge_iot_temperature_count_m a
                left join
                     dim.material m
                on
                     a.material = m.material
                where
                     time = '{year_month}'
                group by
                     time, upper(m.model), temperature
            )'''

    athena_response = submit(sql)
    print_to_log("athena_response: ", athena_response)
    output = {"msg": f"{table_name} submit ok", "Payload": {}}
    output = json.dumps(output)
    step_response = send_task_success(tasktoken, output)
    print_to_log("step_response: ", step_response)


if __name__ == '__main__':
    try:
        event = json.loads(sys.argv[1])
        tasktoken = event.get('TaskToken')
        result_iotwdfb(event)
    except Exception as e:
        print_to_log("athena_submit 失败")
        print_to_log("原因： ", str(e))
        send_task_failure(str(e), f'执行{sys._getframe().f_code.co_filename}错误', tasktoken)
